package 多线程.创建多线程.通过Callable;

import java.util.concurrent.*;

/**
 * 可以有返回值和异常
 */
public class Race {
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ExecutorService es = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = es.submit(task);
        es.shutdown();
        Thread.sleep(2000);
        System.out.println("Main线程执行任务");

        System.out.println("计算结果是"+result.get());

        System.out.println("使用featureTask和ExecutorService");

        ExecutorService executorService = Executors.newCachedThreadPool();
        FutureTask<Integer> futureTask = new FutureTask<>(task);
        executorService.submit(futureTask);
        executorService.shutdown();

        Thread.sleep(2000);
        System.out.println("计算结果是"+futureTask.get());

        System.out.println("使用featureTask和Thread");
        FutureTask<Integer> futureTask1 = new FutureTask<>(task);
        Thread thread = new Thread(futureTask1);
        thread.start();
        System.out.println(futureTask1.get());
    }

}
class Task implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程正在计算");
        int sum=0;
        for(int i=0;i<100;i++){
            sum+=i;
        }
        return sum;
    }
}
